package linkExcel;

import cn.hutool.core.util.StrUtil;
import linkExcel.utils.ExcelUtils;
import linkExcel.utils.ToolUtils;
import linkExcel.vo.ExcelVo;
import org.apache.poi.common.usermodel.HyperlinkType;
import org.apache.poi.ss.usermodel.*;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 针对目标文件夹下所有文件保存至一个sheet
 */
public class SingleMain {

    private static final String EXCEL_PATH = "E:\\引绰济辽\\部门工作\\图纸台账-程悦航\\施工蓝图2023.4.29\\__台账\\图纸台账_枢纽二标.xlsx";
    private static final String SHEET_NAME = "副坝";
    private static final String BEGIN_PATH = "E:\\引绰济辽\\部门工作\\图纸台账-程悦航\\施工蓝图2023.4.29\\1文得根水利枢纽\\3枢纽二标\\2副坝";

    private static List<String> ERROR_ITEMS = new ArrayList<>();

    private static Integer PDF_NUMS = 0;

    private static Integer NO_CODE_NUM = 0;

    public static void main(String[] args) {
        //创建或选择Excel
        Workbook workbook = ExcelUtils.createOrGetExcel(EXCEL_PATH, SHEET_NAME);
        //创建或选择sheet
        Sheet sheet = ExcelUtils.createOrGetSheet(workbook, SHEET_NAME);
        //遍历所有文件
        File file = new File(BEGIN_PATH);
        List<ExcelVo> vos = traverseFolder(file);
        //创建表头
        initTableHeader(sheet);
        // 填充数据
        for (int i = 0; i < vos.size(); i++) {
            ExcelVo vo = vos.get(i);
            Row dataRow = sheet.createRow(i + 1);
            //数据
            dataRow.createCell(0).setCellValue(i + 1);
            dataRow.createCell(1).setCellValue(vo.getName());
            dataRow.createCell(2).setCellValue(vo.getCode());
            dataRow.createCell(3).setCellValue("");
            // 创建超链接
            CreationHelper creationHelper = workbook.getCreationHelper();
            Hyperlink hyperlink = creationHelper.createHyperlink(HyperlinkType.URL);
            try {
                // 为超链接单元格添加超链接
                hyperlink.setAddress(vo.getRelativeLink());
                dataRow.getCell(1).setHyperlink(hyperlink);
                //样式
                CellStyle cellStyle = dataRow.getCell(1).getCellStyle();
                CellStyle newStyle = workbook.createCellStyle();
                newStyle.cloneStyleFrom(cellStyle);
                Font font = workbook.createFont();
                font.setColor(IndexedColors.BLUE.getIndex());
                newStyle.setFont(font);
                dataRow.getCell(1).setCellStyle(newStyle);
            } catch (Exception e) {
                dataRow.createCell(3).setCellValue("超链加注失败，原因为："+e.getCause());
                //样式
                CellStyle cellStyle = dataRow.getCell(3).getCellStyle();
                CellStyle newStyle = workbook.createCellStyle();
                newStyle.cloneStyleFrom(cellStyle);
                Font font = workbook.createFont();
                font.setColor(IndexedColors.RED.getIndex());
                newStyle.setFont(font);
                dataRow.getCell(3).setCellStyle(newStyle);
            }

        }
        // 遍历已填充的单元格
        for (int rowIdx = 0; rowIdx <= vos.size(); rowIdx++) {
            Row dataRow = sheet.getRow(rowIdx); // 获取行
            for (int colIdx = 0; colIdx <= 3; colIdx++) {
                Cell cell = dataRow.getCell(colIdx); // 获取单元格
                // 创建一个新样式并设置黑色边框
                if (cell != null) {
                    CellStyle cellStyle = workbook.createCellStyle();
                    cellStyle.cloneStyleFrom(cell.getCellStyle());
                    cellStyle.setBorderTop(BorderStyle.THIN);
                    cellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
                    cellStyle.setBorderBottom(BorderStyle.THIN);
                    cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
                    cellStyle.setBorderLeft(BorderStyle.THIN);
                    cellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
                    cellStyle.setBorderRight(BorderStyle.THIN);
                    cellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
                    cell.setCellStyle(cellStyle);
                }
            }
        }
        //打印错误结果
        System.out.println("图纸台账录入完成，图号为空数量共计："+NO_CODE_NUM+"条");
        System.out.println("共计[" + (PDF_NUMS - ERROR_ITEMS.size()) + "/" + PDF_NUMS + "]条。" + (ERROR_ITEMS.isEmpty() ? "超链加注全部成功" : "部分超链加注失败，失败内容如下"));
        if (!ERROR_ITEMS.isEmpty()) {
            ERROR_ITEMS.forEach(System.out::println);
        }
        //存入Excel保存
        ExcelUtils.saveExcel(workbook, EXCEL_PATH);
    }

    /**
     * 初始化表头（以及列宽）
     * @param sheet 工作簿
     */
    private static void initTableHeader(Sheet sheet) {
        // 创建表头行
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("序号");
        headerRow.createCell(1).setCellValue("名称");
        headerRow.createCell(2).setCellValue("图号");
        headerRow.createCell(3).setCellValue("备注");

        // 设置列宽度（以字符数为单位）
        sheet.setColumnWidth(0, 8 * 256);
        sheet.setColumnWidth(1, 60 * 256);
        sheet.setColumnWidth(2, 25 * 256);
        sheet.setColumnWidth(3, 15 * 256);
    }

    /**
     * 遍历文件夹下的所有文件
     * @param folder 文件（夹）
     * @return 文件vo对象集合
     */
    private static List<ExcelVo> traverseFolder(File folder) {
        List<ExcelVo> vos = new ArrayList<>();
        if (folder.isDirectory()) {
            System.out.println("\uD83D\uDFE0文件夹：【" + folder.getName() + "】");
            // 获取文件夹内的文件和子文件夹
            File[] subFiles = folder.listFiles();
            if (subFiles != null) {
                for (File file : subFiles) {
                    // 递归遍历子文件夹
                    vos.addAll(traverseFolder(file));
                }
            }
        } else {
            if (folder.getName().endsWith(".pdf")) {
                vos.add(new ExcelVo() {{
                    setName(folder.getName());
                    setCode(ToolUtils.extractGraphNumber(folder.getName()));
                    setRelativeLink(ToolUtils.getRelativePath(folder.getPath(),EXCEL_PATH));
                }});
            }
        }
        return vos;
    }
}
